package com.yswy.app.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.PeriodRuleParams;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.common.utils.UserLockUtils;
import com.yswy.common.vo.dto.PayOrderVo;
import com.yswy.common.vo.dto.RetuenPayOrderVo;
import com.yswy.common.vo.dto.ZfbPayOrderVo;
import com.yswy.app.service.*;
import com.yswy.common.enums.*;
import com.yswy.common.utils.DateUtils;
import com.yswy.common.utils.OrderNoCenter;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.common.wxOrder.V3.GenerateSignVo;
import com.yswy.common.wxOrder.V3.WxPayConfigV3;
import com.yswy.common.wxOrder.V3.wxPayV3Pay.WeChatBasePayData;
import com.yswy.common.wxOrder.V3.wxPayV3Pay.WxPayCommon;
import com.yswy.common.zfbOrder.ZfbKeyVo;
import com.yswy.common.zfbOrder.ZfbOrderUtil;
import com.yswy.domain.entity.*;
import com.yswy.domain.mapper.PayOrderMapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder>
        implements PayOrderService {
    @Autowired
    private VipPriceService vipPriceService;
    @Autowired
    private ZfbPayKeyService zfbPayKeyService;
    @Autowired
    private WxPayKeyService wxPayKeyService;
    @Autowired
    private PayInfo payInfo;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private PayOrderZfbLogService payOrderZfbLogService;
    @Autowired
    private PayOrderWxLogService payOrderWxLogService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private AgreementOrderService agreementOrderService;
    @Autowired
    private AgreementOrderPayLogService agreementOrderPayLogService;

    @Autowired
    private PackageManageService packageManageService;
    @Autowired
    private TgCallBackIdService tgCallBackIdService;
    @Autowired
    private UserDeviceInfoService userDeviceInfoService;
    @Autowired
    private TgChannleService tgChannleService;
    @Autowired
    private TgCallBackKsIdService tgCallBackKsIdService;
    @Autowired
    private TgCallBackHdIdService tgCallBackHdIdService;

    @Autowired
    private UserMoneyService userMoneyService;

    @Override
    @Transactional
    public RetuenPayOrderVo addPayOrder(PayOrderVo payOrderVo, Long userId, String ip) {
        log.info("请求支付参数："+payOrderVo);
        //用户信息
        AppUser appUser = appUserService.getById(userId);
        //支付返回
        RetuenPayOrderVo retuenPayOrderVo = new RetuenPayOrderVo();
        //购买套餐;
        VipPrice vipPrice = vipPriceService.getPeriodRuleParamsByVip(payOrderVo.getGoodsId() , userId);
        log.info("购买阐述："+vipPrice);
        PayOrder payOrder ;
        if (payOrderVo.getPayTerrace() == 0){
            Assert.isTrue(vipPrice.getIsZfbPay() , "此订单不支持支付宝支付");
            payOrder = addZfbOrder(appUser  ,vipPrice ,ip);
        }else if (payOrderVo.getPayTerrace() == 1){
            Assert.isTrue(vipPrice.getIsWxPay() , "此订单不支持微信支付");
            payOrder = addWXOrder(appUser  ,vipPrice ,ip ,  payOrderVo.getPayMethod() );
        }else {
            throw new IllegalArgumentException("支付方式错误");
        }

        retuenPayOrderVo.setPayId(payOrder.getId());
        retuenPayOrderVo.setOrderId(payOrder.getOrderId());
        retuenPayOrderVo.setOrderStatus(payOrder.getOrderStatus());
        retuenPayOrderVo.setPayTerrace(payOrder.getPayTerrace());
        if (payOrder.getPayTerrace() == 0){
            ZfbPayOrderVo zfbPayOrderVo = new ZfbPayOrderVo();
            zfbPayOrderVo.setAppId(payOrder.getAppId());
            zfbPayOrderVo.setTrademsg(payOrder.getPayOrderZfbLog().getTradeStr());
            retuenPayOrderVo.setZfbPayOrderVo(zfbPayOrderVo);
        }else {
            JSONObject jsonObject = JSONObject.parseObject(payOrder.getPayOrderWxLog().getTradeStr());
            GenerateSignVo generateSignVo = jsonObject.toJavaObject(GenerateSignVo.class);
            retuenPayOrderVo.setGenerateSignVo(generateSignVo);
        }

        return retuenPayOrderVo;
    }


    private PayOrder addZfbOrder(AppUser appUser , VipPrice vipPrice ,String ip ){
        String orderRedisKey = RedisConstants.PAYORDER_ZFB+appUser.getId()+"_"+vipPrice.getId();
        //使用支付宝
        ZfbKeyVo zfbKeyVo = null ;
        //支付宝详细参数记录表
        PayOrderZfbLog payOrderZfbLog = null ;
        //周期付款订单ID
        String agreementOrderId = null ;
        //周期付款收款参数
        PeriodRuleParams periodRuleParams = null;
        //订单ID
        String orderId = "ZFB"+OrderNoCenter.getInstance().create();
        //支付字符串
        String payMessage = null ;
        // 订单类型 0 一元限时活动  1 普通产品  2 周期付款产品
        Integer orderType = null ;
        if (redisUtil.hasKey(orderRedisKey)){
            return (PayOrder)redisUtil.getObejct(orderRedisKey);
        }else {
            Integer price = sysConfigService.selectConfigByKey("sys.pay.isTest").equals("1")?1:vipPrice.getPrice();
            if (vipPrice.getIsWithdrawal()){
                log.info("创建签约订单");
                zfbKeyVo = zfbPayKeyService.cutAppId(PayMethodEnums.ZQFK_ZFB_USED.getMessage());
                //获取签约信息
                periodRuleParams =vipPrice.getPeriodRuleParams();
                agreementOrderId = "zq"+OrderNoCenter.getInstance().create();
                //获取支付
                int methodType;
                if (zfbKeyVo.getProductCode().equals(AlipayMethodEnums.CYCLE.getMessage())){
                    methodType =  3;//周期付款
                }else if (zfbKeyVo.getProductCode().equals(AlipayMethodEnums.GENERAL.getMessage())){
                    methodType =  4;//商家扣款
                }else {
                    throw new IllegalArgumentException("支付参数错误");
                }
                payMessage =  ZfbOrderUtil.getPayMessage(zfbKeyVo,orderId,price,
                        vipPrice.getVipName(), payInfo.returnUrl,payInfo.callbackUrl,methodType ,
                        agreementOrderId  , payInfo.agreemenUrl, periodRuleParams);
                if (vipPrice.getIsDisposable()){
                    orderType = 0 ;
                }else {
                    orderType = 2 ;
                }
            }else {
                zfbKeyVo = zfbPayKeyService.cutAppId(PayMethodEnums.PT_ZFB_USED.getMessage());
                payMessage =  ZfbOrderUtil.getPayMessage(zfbKeyVo,orderId,price,
                        vipPrice.getVipName(),payInfo.returnUrl,payInfo.callbackUrl,1 ,
                        null ,null, null   );
                orderType = 1 ;
            }

            //记录支付阐述
            payOrderZfbLog =payOrderZfbLogService.generateOrder(orderId,payMessage,zfbKeyVo ,
                    payInfo.callbackUrl ,appUser.getId().toString() ,vipPrice ,ip);
            //记录订单表
            PayOrder payOrder = new PayOrder();
            payOrder.setOrderId(orderId);
            payOrder.setExternalAgreementNo(agreementOrderId);
            payOrder.setAppId(zfbKeyVo.getAppId());
            payOrder.setOrderStatus(0);
            payOrder.setGoodType(vipPrice.getGoodType());
            payOrder.setOrderType(orderType);
            payOrder.setGoodsId(vipPrice.getId().toString());
            payOrder.setAmount(vipPrice.getPrice());
            payOrder.setUserId(appUser.getId());
            payOrder.setZfbLogId(payOrderZfbLog.getId());
            payOrder.setPayTerrace(0);
            payOrder.setChannel(appUser.getChannel());
            payOrder.setUserPhone(appUser.getUserPhone());
            save(payOrder);
            //记录签约信息
            if (payOrder.getOrderType() != 1){
                agreementOrderService.addUserAgreementLog( vipPrice , payOrder  ,zfbKeyVo);
            }
            //缓存到redis
            payOrderZfbLog.setCreateTime(null);
            payOrder.setPayOrderZfbLog(payOrderZfbLog);
            redisUtil.setForObjectTimeCustom(orderRedisKey, payOrder, 9, TimeUnit.MINUTES);
            redisUtil.setForObjectTimeCustom(RedisConstants.PAYORDER_ZFB+orderId, payOrder, 9, TimeUnit.MINUTES);
            return payOrder;
        }
    }

    private PayOrder addWXOrder(AppUser appUser , VipPrice vipPrice ,String ip,Integer payMethod  ){
        String orderRedisKey = RedisConstants.PAYORDER_WX+appUser.getId()+"_"+vipPrice.getId();
        //使用支付宝
        WxPayConfigV3 wxPayConfigV3 = null ;
        //支付宝详细参数记录表
        PayOrderWxLog payOrderWxLog = null ;
        //订单ID
        String orderId = "WX"+OrderNoCenter.getInstance().create();
        //支付字符串
        GenerateSignVo generateSignVo = null ;
        // 订单类型 0 一元限时活动  1 普通产品  2 周期付款产品
        Integer orderType = null ;
        if (redisUtil.hasKey(orderRedisKey)){
            return (PayOrder)redisUtil.getObejct(orderRedisKey);
        }else {
            Integer price = sysConfigService.selectConfigByKey("sys.pay.isTest").equals("1")?1:vipPrice.getPrice();
            if (vipPrice.getIsWithdrawal()){
                throw new IllegalArgumentException("该订单暂不支持微信支付");
            }else {
                wxPayConfigV3 = wxPayKeyService.cutAppId(WxPayMethodEnums.APP_PAY_USED.getMessage());

                WeChatBasePayData basePayData =new WeChatBasePayData();
                basePayData.setOrderId(orderId);
                basePayData.setPrice(new BigDecimal(price));
                basePayData.setTitle(vipPrice.getVipName());;

                CloseableHttpClient closeableHttpClient = wxPayConfigV3.getWxPayClient();
                if (payMethod == 0){
                    generateSignVo = WxPayCommon.wxJsApiPay(wxPayConfigV3 , basePayData  , appUser.getOpenid(), closeableHttpClient);
                }else if (payMethod == 1){
                    generateSignVo = WxPayCommon.wxAppPay(wxPayConfigV3 , basePayData , closeableHttpClient);
                }else {
                    throw new IllegalArgumentException("支付方式错误");
                }

                orderType = 1 ;
            }
            //记录支付阐述
            payOrderWxLog =payOrderWxLogService.generateOrder(orderId,generateSignVo,wxPayConfigV3 ,
                   appUser.getId().toString() ,vipPrice ,ip);
            //记录订单表
            PayOrder payOrder = new PayOrder();
            payOrder.setOrderId(orderId);
            payOrder.setAppId(wxPayConfigV3.getMchId());
            payOrder.setOrderStatus(0);
            payOrder.setGoodType(vipPrice.getGoodType());
            payOrder.setOrderType(orderType);
            payOrder.setGoodsId(vipPrice.getId().toString());
            payOrder.setAmount(vipPrice.getPrice());
            payOrder.setUserId(appUser.getId());
            payOrder.setZfbLogId(payOrderWxLog.getId());
            payOrder.setPayTerrace(1);
            payOrder.setChannel(appUser.getChannel());
            payOrder.setUserPhone(appUser.getUserPhone());
            save(payOrder);
            //缓存到redis
            payOrderWxLog.setCreateTime(null);
            payOrder.setPayOrderWxLog(payOrderWxLog);
            redisUtil.setForObjectTimeCustom(orderRedisKey, payOrder, 9, TimeUnit.MINUTES);
            redisUtil.setForObjectTimeCustom(RedisConstants.PAYORDER_WX+orderId, payOrder, 9, TimeUnit.MINUTES);
            return payOrder;
        }
    }

    @Override
    public void test(Long payOrderId){
        AgreementOrderPayLog agreementOrderPayLog =
                agreementOrderPayLogService.getOne(
                        new LambdaQueryWrapper<AgreementOrderPayLog>()
                                .eq(AgreementOrderPayLog::getLogId , payOrderId));
        System.out.println(agreementOrderPayLog);
        AgreementOrder agreementOrder = agreementOrderService.getById(agreementOrderPayLog.getAgreementOrderId());
        PayOrder payOrder = addAgreementOrder(agreementOrder , agreementOrderPayLog);
        agreementOrderPayLogService.update(new LambdaUpdateWrapper<AgreementOrderPayLog>()
                .set(AgreementOrderPayLog::getStatusType , 0)
                .set(AgreementOrderPayLog::getPayOrderId ,payOrder.getId() )
                .eq(AgreementOrderPayLog::getLogId,agreementOrderPayLog.getLogId()));
    }

    @Override
    public PayOrder addAgreementOrder(AgreementOrder agreementOrder ,AgreementOrderPayLog agreementOrderPayLog) {
        log.info("创建周期付款订单  "+agreementOrder);
        //用户信息
        AppUser appUser = appUserService.getById(agreementOrder.getUserId());
        if (appUser == null){
            return null ;
        }
        PayOrderZfbLog payOrderZfbLog = payOrderZfbLogService.getOne(new LambdaQueryWrapper<PayOrderZfbLog>()
                .eq(PayOrderZfbLog::getOrderId ,agreementOrder.getOrderId())
                .last("LIMIT 1"));
        ZfbKeyVo zfbKeyVo = zfbPayKeyService.getZfbKeyVo(payOrderZfbLog);
        //订单ID
        String orderId = OrderNoCenter.getInstance().create();
        Integer price = null ;
        if (agreementOrderPayLog.getAgreemenPrice() == null){
            price = agreementOrder.getSingleAmount();
        }else {
            price = agreementOrderPayLog.getAgreemenPrice();
        }
        //获取支付
        String agreementOrderStr =  sysConfigService.selectConfigByKey("sys.pay.agreementOrderStr");
        AlipayTradePayResponse response = ZfbOrderUtil.
                AlipayTradePayRequest(zfbKeyVo,orderId,price,
                        agreementOrderStr, agreementOrder.getAgreementNo() ,payInfo.callbackUrl);
        Integer orderStatus = 0 ;
        if(response.isSuccess()){
            log.info("调用成功");
        } else {
            orderStatus = 4;
            log.info("周期付款订单调用失败  "+response.getSubMsg() + "订单ID ");
        }
        PayOrderZfbLog payOrderZfbLogNew =payOrderZfbLogService.generateAgreementOrder(orderId,response,zfbKeyVo ,
                payInfo.callbackUrl ,appUser.getId().toString() ,price,agreementOrder );
        PayOrder payOrder = new PayOrder();
        payOrder.setOrderId(orderId);
        payOrder.setExternalAgreementNo(agreementOrder.getExternalAgreementNo());
        payOrder.setAppId(zfbKeyVo.getAppId());
        payOrder.setOrderStatus(orderStatus);
        payOrder.setOrderType(3);
        payOrder.setAgreementOrderId(agreementOrder.getId());
        payOrder.setAmount(price);
        payOrder.setUserId(appUser.getId());
        payOrder.setZfbLogId(payOrderZfbLogNew.getId());
        payOrder.setPayTerrace(0);
        payOrder.setGoodType(1);
        payOrder.setChannel(appUser.getChannel());
        payOrder.setUserPhone(appUser.getUserPhone());
        save(payOrder);
        payOrder.setResponse(response);
        return payOrder;
    }

    @Override
    public void delPayOrder() {
        int pageNum = 1;
        int pageSize = 10;
        boolean hasMore = true;
        while (hasMore) {
            Date date = DateUtils.addDateNum(new Date() , DateUnitEnums.DAY.getMessage() , -1);
            // 查询第 pageNum 页数据
            Page<PayOrder> resultPage = baseMapper.selectPage(new Page<>(pageNum, pageSize)
                    , Wrappers.<PayOrder>lambdaQuery()
                            .le(PayOrder::getCreateTime  , date)
                            .eq(PayOrder::getOrderStatus , 0));
            List<PayOrder> dataList = resultPage.getRecords();

            if(dataList.size() == 0)break;
            // 判断是否还有数据
            if (dataList.size() == pageSize) {
                pageNum++;
            } else {
                hasMore = false;
            }
            // 处理数据
            for (PayOrder payOrder : dataList) {
//                delAgreementOrder(payOrder);
            }
        }
    }


    @Override
    public void delAgreementOrder(PayOrder payOrder) {
        log.info("关闭付款订单  "+payOrder.getOrderId());
        PayOrderZfbLog payOrderZfbLog = payOrderZfbLogService.getById(payOrder.getZfbLogId());
        ZfbKeyVo zfbKeyVo = zfbPayKeyService.getZfbKeyVo(payOrderZfbLog);
        //订单ID
        String orderId = payOrder.getOrderId();
        //获取支付
        ZfbOrderUtil.AlipayTradeCloseRequest(zfbKeyVo,orderId);
        payOrder.setOrderStatus(1);
        updateById(payOrder);
        if (payOrder.getOrderType() == 3){
            agreementOrderPayLogService.update(new LambdaUpdateWrapper<AgreementOrderPayLog>()
                    .set(AgreementOrderPayLog::getStatusType , 2)
                    .eq(AgreementOrderPayLog::getPayOrderId,payOrder.getId() ));
            agreementOrderPayLogService.addLastAgreementOrder(payOrder);
        }

    }

    @Override
    public void callbackPayOrder(Integer payTerrace , PayOrderZfbLog payOrderZfbLog , PayOrderWxLog payOrderWxLog) {
        String orderId;
        String alitradeno;
        Integer state;
        String channelIp ;
        if (payTerrace == 0){
            orderId = payOrderZfbLog.getOrderId() ;
            alitradeno = payOrderZfbLog.getAlitradeno();
            state = payOrderZfbLog.getState();
            channelIp = payOrderZfbLog.getChannelIp();
        }else {
            orderId = payOrderWxLog.getOrderId() ;
            alitradeno = payOrderWxLog.getAlitradeno();
            state = payOrderWxLog.getState();
            channelIp = payOrderWxLog.getChannelIp();
        }

        PayOrder payOrder = getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderId, orderId));
        if (payOrder == null) {
            log.info("支付回调订单"+orderId+"不存在");
            return;
        }else {
            payOrder.setPayOrderZfbLog(payOrderZfbLog);
            payOrder.setPayOrderWxLog(payOrderWxLog);
        }
        if (payOrder.getOrderStatus() != 0 && payOrder.getOrderStatus() != 1) {
            log.info("支付回调订单"+orderId+"订单已处理重复回调");
            return;
        }

        if (state == PaymentStateEnums.TRADE_FINISHED.getCode()) {//交易关闭
            log.info("交易关闭" + payOrder.getOrderId() + " 状态: " + state);
            payOrder.setOrderStatus(1);
            if (payOrder.getOrderType() == 3){
                agreementOrderPayLogService.update(new LambdaUpdateWrapper<AgreementOrderPayLog>()
                        .set(AgreementOrderPayLog::getStatusType , 2)
                        .eq(AgreementOrderPayLog::getPayOrderId,payOrder.getId() ));
            }
        } else if (state == PaymentStateEnums.TRADE_SUCCESS.getCode() || state == PaymentStateEnums.TRADE_FINISHED.getCode()) {//交易成功
            log.info("回调成功" + payOrder.getOrderId() + " 状态: " + state);
            payOrder.setPayTime(new Date());
            payOrder.setOrderStatus(2);
            payOrder.setAlitradeno(alitradeno);
            //回调成功成功业务
            callbackStatusOK(payOrder,channelIp);
            //记录收款金额
            if (payOrder.getPayTerrace() == 0) {
                //记录支付宝收款记录
                zfbPayKeyService.recordPayMoney(payOrder.getAmount(), payOrder.getAppId());
            } else if (payOrder.getPayTerrace() == 1 ) {
                //记录微信收款记录
                wxPayKeyService.recordPayMoney(payOrder.getAmount(), payOrder.getAppId());
            }
        } else {
            log.info("状态异常" + payOrder.getOrderId() + " 状态: " + state);
            payOrder.setOrderStatus(1);
            if (payOrder.getOrderType() == 3){
                agreementOrderPayLogService.update(new LambdaUpdateWrapper<AgreementOrderPayLog>()
                        .set(AgreementOrderPayLog::getStatusType , 2)
                        .eq(AgreementOrderPayLog::getPayOrderId,payOrder.getId() ));
                agreementOrderPayLogService.addLastAgreementOrder(payOrder);
            }
        }

        String key;
        if (payOrder.getPayTerrace() == 0){
            key = RedisConstants.PAYORDER_ZFB;
        }else {
            key = RedisConstants.PAYORDER_WX;
        }
        redisUtil.delete(key+payOrder.getUserId()+"_"+payOrder.getGoodsId());
        redisUtil.delete(key+payOrder.getOrderId());
        updateById(payOrder);

    }
    public void callbackStatusOK(PayOrder payOrder , String ip){

        if (payOrder.getGoodType() == 0){
            //0 金币购买
            addCodeMoney(payOrder);
        }else {
            //1 vip购买
            addTheaterVip(payOrder);
        }
        //回传付费
        tgCallBack( ip,  payOrder);
    }

    //购买金币
    private void addCodeMoney(PayOrder payOrder){
        Long userId = payOrder.getUserId();

        VipPrice vipPrice ;
        if (payOrder.getPayTerrace() == 0){
            JSONObject jsonObject = JSONObject.parseObject(payOrder.getPayOrderZfbLog().getItemInfo());
            vipPrice = jsonObject.toJavaObject(VipPrice.class);
            //解除周期付款
//                agreementOrderService.userAgreementUnOldOrder(userId,payOrder.getExternalAgreementNo());
        }else {
            JSONObject jsonObject = JSONObject.parseObject(payOrder.getPayOrderWxLog().getItemInfo());
            vipPrice = jsonObject.toJavaObject(VipPrice.class);
        }
        if (vipPrice.getIsDisposable() == true){
            String key = RedisConstants.firstPay+userId ;
            redisUtil.setForObjectTimeCustom(key, 1, 1, TimeUnit.DAYS);
        }
        //添加金币
        userMoneyService.addByPay(userId ,vipPrice.getMoneyCode() );
    }

    //会员开通
    private void addTheaterVip(PayOrder payOrder){
        Long userId = payOrder.getUserId();
        if (payOrder.getOrderType() == 3){
            AgreementOrder agreementOrder = agreementOrderService.getById(payOrder.getAgreementOrderId());
            if (agreementOrder.getAgreemenType() == 0){
                appUserService.addVipTime(agreementOrder);
            }else {
                AgreementOrderPayLog agreementOrderPayLog = agreementOrderPayLogService
                        .getOne(new LambdaQueryWrapper<AgreementOrderPayLog>()
                                .eq(AgreementOrderPayLog::getPayOrderId , payOrder.getId()));
                appUserService.addVipTime(userId ,agreementOrderPayLog);
            }
            //修改签约订单状态
            agreementOrderPayLogService.update(new LambdaUpdateWrapper<AgreementOrderPayLog>()
                    .set(AgreementOrderPayLog::getStatusType , 1)
                    .eq(AgreementOrderPayLog::getPayOrderId,payOrder.getId()));
            //创建新的签约任务
            agreementOrderPayLogService.addLastAgreementOrder(payOrder);
        }else {
            VipPrice vipPrice ;
            if (payOrder.getPayTerrace() == 0){
                JSONObject jsonObject = JSONObject.parseObject(payOrder.getPayOrderZfbLog().getItemInfo());
                vipPrice = jsonObject.toJavaObject(VipPrice.class);
                //解除周期付款
//                agreementOrderService.userAgreementUnOldOrder(userId,payOrder.getExternalAgreementNo());
            }else {
                JSONObject jsonObject = JSONObject.parseObject(payOrder.getPayOrderWxLog().getItemInfo());
                vipPrice = jsonObject.toJavaObject(VipPrice.class);
            }
            //添加会员时间
            appUserService.addVipTime(userId ,vipPrice );
            //解除周期付款
            agreementOrderService.userAgreementUnOldOrder(payOrder.getUserId(),payOrder.getExternalAgreementNo());
        }
    }
    //付费回传逻辑
    public void tgCallBack(String ip, PayOrder payOrder){
        AppUser appUser = appUserService.getById(payOrder.getUserId());
        try {
            Boolean isCallBackDisposable = packageManageService.isCallBackDisposable(payOrder.getChannel());
            if (payOrder.getOrderType() == 3){
                if (!isCallBackDisposable){
                    AgreementOrderPayLog agreementOrderPayLog = agreementOrderPayLogService.getOne(new LambdaQueryWrapper<AgreementOrderPayLog>()
                            .eq(AgreementOrderPayLog::getPayOrderId , payOrder.getId()));
                    if (agreementOrderPayLog!= null){
                        if (agreementOrderPayLog.getPayments() == 0){
                            UserDeviceInfo userDeviceInfo = userDeviceInfoService.getOne(new LambdaQueryWrapper<UserDeviceInfo>()
                                    .eq(UserDeviceInfo::getUserId , payOrder.getUserId()));

                            //判断用户来源
//                            Integer integer =  tgChannleService.getUserSource(appUser.getId(), appUser.getCreateIp() , 1);
//                            if (integer == 0){
//                                tgCallBackIdService.callBackPay(appUser.getId() ,appUser.getCreateIp(), payOrder.getAmount());
//                            }else if (integer == 1){
//                                tgCallBackKsIdService.ksCallBackPay(appUser.getId() , appUser.getCreateIp(), payOrder.getAmount());
//                            }else if (integer == 2){
//                                tgCallBackHdIdService.hdCallBackPay(appUser.getId() , ip, payOrder.getAmount());
//                            }
                        }
                    }
                }
            }else {
                //判断用户来源
                Integer integer =  tgChannleService.getUserSource(appUser.getId(), ip, 1);
                if (integer == 0){
                    tgCallBackIdService.callBackPay(appUser.getId() ,ip, payOrder.getAmount());
                }else if (integer == 1){
                    tgCallBackKsIdService.ksCallBackPay(appUser.getId() , ip, payOrder.getAmount());
                }else if (integer == 2){
                    tgCallBackHdIdService.hdCallBackPay(appUser.getId() , ip, payOrder.getAmount());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Override
    public String checkingPayOrder(String orderId, Long userId) {
        PayOrder payOrder = null ;
        if (redisUtil.hasKey(RedisConstants.PAYORDER_ZFB+orderId)){
            payOrder = (PayOrder)redisUtil.getObejct("PAYORDER:"+orderId);
        }else {
            payOrder = getOne(new LambdaQueryWrapper<PayOrder>()
                    .eq(PayOrder::getOrderId , orderId));
        }
        if (payOrder == null){
            log.info( "订单不存在：" + orderId);
            return "false" ;
        }
        // 订单状态 -1 取消  0 待支付   1 交易关闭  2 支付成功(daifahuo)   3已完成(shouhuo)  4待收货
        if (payOrder.getOrderStatus() == 2 ||
                payOrder.getOrderStatus() == 3 ){
            return "true" ;
        }else {
            return "false" ;
        }
    }

    @Override
    public Boolean isPayOrder(Long userId) {
        Integer count = 0 ;
        String key = RedisConstants.firstPay+userId ;
        if (redisUtil.hasKey(key)){
            count = (Integer)redisUtil.getObejct(key);
        }else {
            count = baseMapper.countIsPayDisposable(userId);
            System.out.println(count);
        }

        if (count>0){
            redisUtil.setForObjectTimeCustom(key, count, 1, TimeUnit.DAYS);
            return true;
        }else {
            return false ;
        }
    }




}
